package com.jee.ssm.modules.users.controller;

import com.github.pagehelper.PageInfo;
import com.jee.ssm.model.Department;
import com.jee.ssm.model.EvaluateUser;
import com.jee.ssm.model.Users;
import com.jee.ssm.model.UsersCountDto;
import com.jee.ssm.modules.department.services.DepartmentService;
import com.jee.ssm.modules.evaluateUser.services.EvaluateUserService;
import com.jee.ssm.modules.users.services.UsersService;
import com.jee.ssm.common.log.AdminControllerLog;
import com.jee.ssm.modules.ssm.controller.AdminBaseController;
import com.jee.ssm.model.json.Tip;
import com.jee.ssm.model.param.ParamMap;
import com.jee.ssm.common.utils.UUIDFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
* 用户管理 Controller
* @author GaoXiang
* @version 1.0
*/
@Controller
@RequestMapping("/users")
public class UsersController extends AdminBaseController<Users> {

    @Resource
    private DepartmentService departmentService;


    /**
     * 进入用户添加页面 携带一个生成的id --> longId
     * @param model 返回的实体容器
     * @return 添加页面
     */
    @RequestMapping(value="/add")
    @RequiresPermissions("users:add")
    public String add(ModelMap model){

        PageInfo<Department> pageInfo = departmentService.list(new HashMap());
        model.put("departmentList",pageInfo.getList());
        model.put("longId", UUIDFactory.getStringId());
        return "manager/users/add";
    }




    /**
     * 进入用户编辑页面
     * @param model 返回用户的容器
     * @param id 用户id
     * @return 编辑页面
     */
    @RequestMapping(value="/edit")
    @RequiresPermissions("users:edit")
    public String edit(ModelMap model, @RequestParam String id) {

        PageInfo<Department> pageInfo = departmentService.list(new HashMap());
        model.put("departmentList",pageInfo.getList());

        model.put("data",usersService.selectById(id));
        return "manager/users/edit";
    }


    /**
     * 用户添加
     * @param users 带id的用户对象
     * @return 成功状态
     */
    @RequestMapping(value="/save")
    @ResponseBody
    @RequiresPermissions("users:add")
    @AdminControllerLog(description = "添加用户" )
    public Tip save(Users users,String firstImg)  {

        try {
            users.setTotalScore(0);
            users.setHeadImg(firstImg);
            users.setCreateTime(new Date());
            Department department = departmentService.selectById(users.getOrgId());
            if(department != null){
                users.setDepartmentName(department.getName());
            }
            usersService.insert(users);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"添加失败！");
        }
    }


    /**
     * 描述：  上传人员图片
     * 创建时间：2020/10/10  YanZengBao
     * 修改时间：2020/10/10  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/headImage")
    @ResponseBody
    public Tip companyImage(@RequestParam(name = "file") MultipartFile file, HttpServletRequest request) throws Exception{
        try {
            String filename = file.getOriginalFilename();
            String name = UUIDFactory.getStringId() + "_" + System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
            String url = "/images/users/" + name;
            String realPath = request.getSession().getServletContext().getRealPath(url);
            File img = new File(realPath);
            if (!img.exists() && !img.isDirectory()) {
                img.mkdirs();
            }
            file.transferTo(img);
            return new Tip(url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Tip(2,"上传失败！");
        }
    }


    @RequestMapping(value = "/delImage")
    @ResponseBody
    public Tip delImage(String url) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String realPath = request.getSession().getServletContext().getRealPath(url);
        File file = new File(realPath);
        if(file.exists()) {
            file.delete();
        }
        return new Tip();
    }

    /**
     * 描述： 生成二维码页面
     * 创建时间：2020/10/11  YanZengBao
     * 修改时间：2020/10/11  YanZengBao 加注释
     * 修改时间：
     */
    @RequestMapping(value = "/enterUsersCode")
    public String enterUsersCode(String userId, ModelMap modelMap) {
        //modelMap.put("users", users);
        modelMap.put("userId", userId);
        return "manager/users/enterUsersCode";
    }

    /**
     * 根据 id 修改用户
     * @param users 带id的用户对象
     * @return 成功状态
     */
    @RequestMapping(value="/update")
    @ResponseBody
    @RequiresPermissions("users:edit")
    @AdminControllerLog(description = "修改用户" )
    public Tip update(Users users) {

        try {
            //判断职工姓名是否修改
            Users selectById = usersService.selectById(users.getId());
            if(selectById != null){
                if(!users.getName().equals(selectById.getName())){
                    List<EvaluateUser> evaluateUsers = evaluateUserService.selectByUserId(users.getId());
                    if(evaluateUsers != null && !evaluateUsers.isEmpty()){
                        for (EvaluateUser e:evaluateUsers) {
                            e.setWorkersName(users.getName());
                            evaluateUserService.updateById(e);
                        }
                    }
                }
            }

            Department department = departmentService.selectById(users.getOrgId());
            if(department != null){
                users.setDepartmentName(department.getName());
            }
            usersService.updateById(users);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"修改失败！");
        }

    }


    /**
     * 根据 id 删除用户
     * @param id 用户id
     * @return 成功状态
     */
    @RequestMapping(value="/delete")
    @ResponseBody
    @RequiresPermissions("users:delete")
    @AdminControllerLog(description = "删除用户" )
    public Tip delete(@RequestParam String id) {

        try {
            usersService.deleteById(id);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"删除失败！");
        }

    }


    /**
     * 根据 id 列表批量删除
     * @param ids 用户id List
     * @return 成功状态
     */
    @RequestMapping(value="/deleteByIds")
    @ResponseBody
    @RequiresPermissions("users:delete")
    @AdminControllerLog(description = "批量删除用户" )
    public Tip deleteByIds(@RequestParam("ids") List<String> ids) {

        try {
            usersService.deleteByIds(ids);
            return new Tip();
        } catch (Exception e) {
            //e.printStackTrace();
            return new Tip(1,"批量删除失败！");
        }

    }


    /**
     * 根据 id 查找用户
     * @param id 用户id
     * @return 用户对象 json
     */
    @RequestMapping(value="/findJson")
    @ResponseBody
    @RequiresPermissions("users:list")
    public Users find(@RequestParam String id) {

        return usersService.selectById(id);
    }


    /**
     * 获取用户列表 获取全部 不分页
     * @param request 请求参数
     * @return 用户列表页面
     */
    @RequestMapping(value="/all")
    @RequiresPermissions("users:list")
    public String all(HttpServletRequest request,ModelMap modelMap) {

        return list(request,modelMap,1,0);
    }


    /**
     * 获取用户列表 分页
     * @param request 请求参数
     * @param page 第几页
     * @param size 每页大小
     * @return 用户列表页面
     */
    @RequestMapping(value="/list")
    @RequiresPermissions("users:list")
    public String list(HttpServletRequest request,ModelMap modelMap,Integer page,Integer size) {
        ParamMap paramMap = new ParamMap(request);
        PageInfo<Department> pageInfo = departmentService.list(new HashMap());
        modelMap.put("departmentList" ,pageInfo.getList());
        PageInfo<Users> usersPageInfo = usersService.list(paramMap, page, size);
        modelMap.put("pageInfo",usersPageInfo);
        modelMap.putAll(paramMap);
        return "manager/users/list";
    }


    @RequestMapping(value = "/exportEcxel")
    public void exportEcxel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ParamMap paramMap = new ParamMap(request);
        List<UsersCountDto> usersCountDtos = new ArrayList<>();

        List<Users> list = usersService.list(paramMap).getList();
        if(list != null && !list.isEmpty()){
            for (Users users : list) {
                if(users != null){
                    paramMap.put("workersId",users.getId());
                    UsersCountDto usersCountDto = new UsersCountDto();
                    usersCountDto.setUserName(users.getName());
                    //不满意
                    paramMap.put("ratingType","0");
                    int bmy = evaluateUserService.list(paramMap).getList().size();
                    usersCountDto.setBumanyiNum(bmy);
                    //一般
                    paramMap.put("ratingType","1");
                    int yiban = evaluateUserService.list(paramMap).getList().size();
                    usersCountDto.setYibanNum(yiban);
                    //满意
                    paramMap.put("ratingType","2");
                    int manyi = evaluateUserService.list(paramMap).getList().size();
                    usersCountDto.setGoodNum(manyi);
                    //非常满意
                    paramMap.put("ratingType","3");
                    int very = evaluateUserService.list(paramMap).getList().size();
                    usersCountDto.setVeryGoodNum(very);
                    usersCountDto.setTotalNum(very + manyi + yiban + bmy);
                    usersCountDtos.add(usersCountDto);
                }
            }
        }

        String originFileUrl = request.getServletContext().getRealPath("/download/info.xlsx");
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), UsersCountDto.class, usersCountDtos);
        FileOutputStream fos = new FileOutputStream(originFileUrl);
        workbook.write(fos);

        String fileName = "评分数量统计导出.xls";
        fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        //设置文件MIME类型
        response.setContentType(request.getServletContext().getMimeType(fileName));
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //读取文件
        InputStream in = new FileInputStream(originFileUrl);
        OutputStream out = response.getOutputStream();
        //写文件
        int b;
        while((b=in.read()) != -1) {
            out.write(b);
        }
        fos.close();
        in.close();
        out.close();
    }

    /**
     * 跳转统计评价页面
     * @param model
     * @return
     */
    @RequestMapping(value="/toCountEvaluate")
    public String toCountEvaluate(String userId, ModelMap model){
        model.put("userId",userId);
        return "manager/users/countEvaluate";
    }

    /**
     * 获取统计数据
     * @param type
     * @param userId
     * @param start
     * @param end
     * @return
     */
    @RequestMapping(value="/countEvaluate_pie")
    @ResponseBody
    public Tip countEvaluate_pie(Integer type, String userId, Date start, Date end){
        Tip tip = new Tip();
        if (type == 3){
            tip = usersService.countEvaluate_pie(userId,start,end);
        }else{
            tip = usersService.countToday(userId,type);
        }

        return tip;
    }


    //---------------------------- property -------------------------------

    @Resource
    private UsersService usersService;
    @Resource
    private EvaluateUserService evaluateUserService;

}
